package com.example.todoappserver.service;

import com.alibaba.fastjson.JSONObject;
import com.example.todoappserver.dao.TodoDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ITodoServiceImp implements ITodoService {

    @Autowired
    TodoDao todoDao;

    public List<Map<String,String>>  getTodoList() {
        List<Map<String,String>>  resList = new ArrayList<>();
        if (todoDao.getTodoList().isEmpty()){
            return  resList;
        }
        resList = todoDao.getTodoList();
        return resList;
    }


    public HashMap<String, Object> addTodo(HttpServletRequest Request) {
        Map<String, Object> todoMap = new HashMap<String, Object>();
        JSONObject object=  JSONObject.parseObject(Request.getParameter("todo"));
        if (todoDao.addTodo(object.get("todo_text").toString())!=0){
            todoMap.put("code","ok");
            todoMap.put("msg","添加成功");
        }else {
            todoMap.put("code","err");
            todoMap.put("msg","添加失败");
        }
        return (HashMap<String, Object>) todoMap;
    }

    public HashMap<String, Object> updateTodo(HttpServletRequest Request) {
        HashMap<String, Object> result = new HashMap();
        Map mapObj = JSONObject.parseObject(Request.getParameter("todo"),Map.class);
        if (todoDao.updateTodo(mapObj)!=0){
            result.put("code","ok");
            result.put("msg","修改成功");
        }else {
            result.put("code","err");
            result.put("msg","修改失败");
        }
        return result;
    };
}
